/**
 * 登录操作
 * 1. wx.login 返回 code
 * 2. 获取 openid 返回 openid
 * 3. 系统登录 返回token
 */

var config = require('../config.js');
var request = require('../utils/request.js');

function LmmLogin(setusercallback , shopId, userInfo , province , city , county) {
  
  return new Promise((resoleve, reject)=> {
    //第一步
    let wxloginRes = wxLogin();
    wxloginRes.then(res => {
      //第二步
      let getOpenIdRes = getOpenId(res.code, shopId);
      getOpenIdRes.then(res => {
        //第三部
        let shopkey = wx.getStorageSync('shopkey');
        let unionId = wx.getStorageSync("openId");
        let wxname = userInfo.nickName;
        let photo = userInfo.avatarUrl;

        var t = {
          openId: unionId,
          shopId: shopId,
          wxname: wxname,
          photo: photo,
          province: province,
          city: city,
          area: county
        };

        console.log('thirdlogin params')  
        console.log(t)
      
        if (shopkey) {
          t.shoppingKey = shopkey
        }
        let turl = config.thirdLoginUrl;

        request.requestPost(turl, t)
          .then(data => {
            console.log('thirdLoginUrl')
            console.log(data);
            // app.globalData.user = data.user;
            setusercallback(data.user);
            wx.setStorageSync('shopkey', data.shoppingKey);
            wx.setStorageSync('token', data.token);
            console.log('thirdLogin success');
            resoleve({})
          }).catch(message => {
            console.log('thirdLogin catch')
            console.log(message);
            reject(message);
          })
      }).catch(msg => {
        console.log(msg)
        reject(msg);
      })
    }).catch(msg => {
      console.log('微信登录出错')
      reject('微信登录出错')
    });


  });

  
}


function wxLogin() {
  return new Promise((resoleve, reject) => {
    wx.login({
      success: res => {
        console.log('微信登录success');
        console.log(res);
        resoleve(res);
      },
      fail: function () {
        console.log('微信登录fail');
        reject('微信登录fail')
      }
    });
  });

}


function getOpenId(code, shopId) {
  return new Promise((resoleve, reject) => {
    let params = { code: code, shopId: shopId }
    let url = config.getOpenidUrl;
    request.requestPost(url, params)
      .then(data => {
        console.log('getOpenId Success')
        console.log(data);
        wx.setStorageSync('sessionKey', data.session_key);
        wx.setStorageSync('openId', data.openid);
        resoleve(data);
      }).catch(message => {
        console.log('getOpenId  Catch')
        console.log(message);
        reject(message);
      });
  })
}



module.exports = {
  lmmLogin: LmmLogin,
}